package com.hwpt.chesedemo.presentation.screen

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.hwpt.chesedemo.presentation.navigation.Routes
import com.hwpt.chesedemo.presentation.viewmodel.BluetoothViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BluetoothScreen(
    navController: NavController
) {
    val viewModel: BluetoothViewModel = hiltViewModel()
    val state by viewModel.state.collectAsState()
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val filteredDevices = remember(state.devices, state.showUnknownDevices) {
        if (!state.showUnknownDevices) {
            state.devices.filter { device ->
                device.name != "未知设备" && device.name.isNotBlank()
            }
        } else {
            state.devices
        }
    }

    // 权限请求Launcher
    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val grantResults = IntArray(permissions.size) { index ->
            if (permissions.values.elementAt(index)) {
                android.content.pm.PackageManager.PERMISSION_GRANTED
            } else {
                android.content.pm.PackageManager.PERMISSION_DENIED
            }
        }
        viewModel.onPermissionsResult(grantResults)
    }

    // 蓝牙启用请求Launcher
    val enableBluetoothLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        viewModel.onBluetoothEnabled(result.resultCode == android.app.Activity.RESULT_OK)
    }

    // 初始化Launcher和广播接收器
    LaunchedEffect(Unit) {
        viewModel.setPermissionLauncher(permissionLauncher)
        viewModel.setEnableBluetoothLauncher(enableBluetoothLauncher)
        viewModel.registerReceiver(context)

        // 新增：延迟一段时间后检查并请求初始权限
        launch {
            delay(300) // 延迟300ms确保UI已加载
            viewModel.requestInitialPermissionsIfNeeded()
        }
    }

    // 清理广播接收器
    DisposableEffect(Unit) {
        onDispose {
            viewModel.unregisterReceiver(context)
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(Color(0xFF6A11CB), Color(0xFF2575FC))
                )
            )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(24.dp),
            verticalArrangement = Arrangement.Top
        ) {
            // 标题
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(
                    onClick = { navController.navigateUp() },
                    modifier = Modifier
                        .size(40.dp)
                        .background(
                            Color.White.copy(alpha = 0.2f),
                            RoundedCornerShape(10.dp)
                        )
                ) {
                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "返回",
                        tint = Color.White
                    )
                }

                Text(
                    text = "蓝牙调试",
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier.weight(1f),
                    textAlign = androidx.compose.ui.text.style.TextAlign.Center
                )

                // 占位空间保持对称
                Spacer(modifier = Modifier.size(40.dp))
            }

            Spacer(modifier = Modifier.height(24.dp))

            // 状态信息卡片
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFF5A6EE1).copy(alpha = 0.9f)
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                border = BorderStroke(1.dp, Color.White.copy(alpha = 0.3f))
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(20.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    // 蓝牙状态
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.Bluetooth,
                                contentDescription = "蓝牙",
                                modifier = Modifier.size(24.dp),
                                tint = if (state.isBluetoothEnabled) Color(0xFF4CAF50) else Color(0xFF757575)
                            )
                            Text(
                                text = "蓝牙状态",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.SemiBold,
                                color = Color.White
                            )
                        }
                        Text(
                            text = state.bluetoothStatus,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = when {
                                state.isBluetoothEnabled -> Color(0xFF4CAF50)
                                state.isBluetoothAvailable -> Color(0xFFFF9800)
                                else -> Color(0xFFF44336)
                            }
                        )
                    }

                    // 权限状态
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.Security,
                                contentDescription = "权限",
                                modifier = Modifier.size(24.dp),
                                tint = if (state.isScanButtonEnabled) Color(0xFF4CAF50) else Color(0xFF757575)
                            )
                            Text(
                                text = "权限状态",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.SemiBold,
                                color = Color.White
                            )
                        }
                        Text(
                            text = state.permissionStatus,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = when {
                                state.isScanButtonEnabled -> Color(0xFF4CAF50)
                                state.permissionStatus.contains("需要") -> Color(0xFFF44336)
                                else -> Color(0xFF757575)
                            }
                        )
                    }

                    // 错误消息
                    state.errorMessage?.let { error ->
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.Error,
                                contentDescription = "错误",
                                tint = Color(0xFFFF9800),
                                modifier = Modifier.size(24.dp)
                            )
                            Text(
                                text = error,
                                color = Color(0xFFFF9800),
                                fontSize = 14.sp,
                                modifier = Modifier.weight(1f),
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 已绑定设备卡片
            if (state.hasSavedDevice) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(16.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFF4CAF50).copy(alpha = 0.9f)
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                    border = BorderStroke(1.dp, Color.White.copy(alpha = 0.3f))
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(20.dp),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(12.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Link,
                                    contentDescription = "已绑定",
                                    tint = Color.White,
                                    modifier = Modifier.size(24.dp)
                                )
                                Text(
                                    text = "已绑定设备",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color.White
                                )
                            }

                            // 进入设备详情按钮
                            IconButton(
                                onClick = {
                                    val encodedName = state.savedDeviceName.replace("/", "_")
                                    navController.navigate("${Routes.DEVICE_DETAIL}/${state.savedDeviceAddress}/${encodedName}")
                                },
                                modifier = Modifier
                                    .size(40.dp)
                                    .background(
                                        Color.White.copy(alpha = 0.2f),
                                        RoundedCornerShape(10.dp)
                                    )
                            ) {
                                Icon(
                                    Icons.Default.ArrowForward,
                                    contentDescription = "进入详情",
                                    tint = Color.White
                                )
                            }
                        }

                        Text(
                            text = state.savedDeviceName,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.SemiBold,
                            color = Color.White
                        )

                        Text(
                            text = "MAC: ${state.savedDeviceAddress}",
                            fontSize = 14.sp,
                            color = Color.White.copy(alpha = 0.8f)
                        )

                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Button(
                                onClick = {
                                    scope.launch {
                                        val device = viewModel.connectSavedDevice()
                                        device?.let {
                                            val encodedName = it.name?.replace("/", "_") ?: "未知设备"
                                            navController.navigate("${Routes.DEVICE_DETAIL}/${it.address}/${encodedName}")
                                        }
                                    }
                                },
                                modifier = Modifier.weight(1f),
                                enabled = state.isScanButtonEnabled,
                                shape = RoundedCornerShape(12.dp),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = Color.White.copy(alpha = 0.9f),
                                    contentColor = Color(0xFF5A6EE1)
                                ),
                                elevation = ButtonDefaults.buttonElevation(
                                    defaultElevation = 4.dp,
                                    pressedElevation = 2.dp
                                )
                            ) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.Center
                                ) {
                                    Icon(Icons.Default.Link, contentDescription = null, modifier = Modifier.size(18.dp))
                                    Spacer(modifier = Modifier.width(8.dp))
                                    Text("连接并进入详情", fontWeight = FontWeight.SemiBold)
                                }
                            }

                            Button(
                                onClick = { viewModel.unbindDevice() },
                                modifier = Modifier.weight(1f),
                                shape = RoundedCornerShape(12.dp),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = Color(0xFFF44336).copy(alpha = 0.9f),
                                    contentColor = Color.White
                                ),
                                elevation = ButtonDefaults.buttonElevation(
                                    defaultElevation = 4.dp,
                                    pressedElevation = 2.dp
                                )
                            ) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.Center
                                ) {
                                    Icon(Icons.Default.Delete, contentDescription = null, modifier = Modifier.size(18.dp))
                                    Spacer(modifier = Modifier.width(8.dp))
                                    Text("解除绑定", fontWeight = FontWeight.SemiBold)
                                }
                            }
                        }
                    }
                }
                Spacer(modifier = Modifier.height(16.dp))
            }

            // 扫描控制卡片
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFF5A6EE1).copy(alpha = 0.9f)
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                border = BorderStroke(1.dp, Color.White.copy(alpha = 0.3f))
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(20.dp),
                    verticalArrangement = Arrangement.spacedBy(20.dp)
                ) {
                    // 扫描按钮
                    Button(
                        onClick = { viewModel.toggleScan() },
                        modifier = Modifier.fillMaxWidth(),
                        enabled = state.isScanButtonEnabled,
                        shape = RoundedCornerShape(12.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (state.isScanning)
                                Color(0xFFF44336).copy(alpha = 0.9f)
                            else
                                Color(0xFF4CAF50).copy(alpha = 0.9f),
                            contentColor = Color.White
                        ),
                        elevation = ButtonDefaults.buttonElevation(
                            defaultElevation = 6.dp,
                            pressedElevation = 3.dp
                        )
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Center,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            if (state.isScanning) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(20.dp),
                                    strokeWidth = 3.dp,
                                    color = Color.White
                                )
                                Spacer(modifier = Modifier.width(12.dp))
                            }
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(2.dp)
                            ) {
                                Text(
                                    text = if (state.isScanning) "停止扫描" else "扫描蓝牙设备",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Bold
                                )

                                if (!state.isScanButtonEnabled) {
                                    Text(
                                        text = "请确保蓝牙已开启并授予权限",
                                        fontSize = 12.sp,
                                        color = Color.White.copy(alpha = 0.8f)
                                    )
                                }
                            }
                        }
                    }

                    // 隐藏未知设备开关
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Icon(
                                imageVector = if (state.showUnknownDevices)
                                    Icons.Default.Visibility
                                else
                                    Icons.Default.VisibilityOff,
                                contentDescription = "显示隐藏",
                                tint = Color.White,
                                modifier = Modifier.size(24.dp)
                            )
                            Column {
                                Text(
                                    text = if (state.showUnknownDevices) "显示所有设备" else "隐藏未知设备",
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.SemiBold,
                                    color = Color.White
                                )
                                if (!state.showUnknownDevices) {
                                    Text(
                                        text = "已隐藏未知设备",
                                        fontSize = 12.sp,
                                        color = Color.White.copy(alpha = 0.8f)
                                    )
                                }
                            }
                        }

                        Switch(
                            checked = state.showUnknownDevices,
                            onCheckedChange = { viewModel.toggleShowUnknownDevices() },
                            colors = SwitchDefaults.colors(
                                checkedThumbColor = Color(0xFF4CAF50),
                                checkedTrackColor = Color.White.copy(alpha = 0.5f),
                                uncheckedThumbColor = Color(0xFF757575),
                                uncheckedTrackColor = Color.White.copy(alpha = 0.3f)
                            )
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 设备列表区域
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFF5A6EE1).copy(alpha = 0.9f)
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                border = BorderStroke(1.dp, Color.White.copy(alpha = 0.3f))
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(20.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    // 设备列表标题
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.Devices,
                                contentDescription = "设备",
                                modifier = Modifier.size(24.dp),
                                tint = Color.White
                            )
                            Text(
                                text = "扫描到的设备",
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color.White
                            )
                        }

                        Text(
                            text = "(${filteredDevices.size}个)",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.SemiBold,
                            color = Color.White
                        )
                    }

                    // 设备列表或空状态
                    if (filteredDevices.isEmpty()) {
                        if (state.isScanning) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(150.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.spacedBy(16.dp)
                                ) {
                                    CircularProgressIndicator(
                                        modifier = Modifier.size(48.dp),
                                        strokeWidth = 4.dp,
                                        color = Color.White
                                    )
                                    Text(
                                        text = if (!state.showUnknownDevices)
                                            "正在扫描并过滤未知设备..."
                                        else
                                            "正在扫描设备...",
                                        color = Color.White,
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                    if (!state.showUnknownDevices && state.devices.isNotEmpty()) {
                                        Text(
                                            text = "过滤掉了 ${state.devices.size - filteredDevices.size} 个未知设备",
                                            fontSize = 14.sp,
                                            color = Color.White.copy(alpha = 0.8f)
                                        )
                                    }
                                }
                            }
                        } else {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(150.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.spacedBy(12.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.DeviceUnknown,
                                        contentDescription = "无设备",
                                        tint = Color.White.copy(alpha = 0.7f),
                                        modifier = Modifier.size(48.dp)
                                    )
                                    Text(
                                        text = if (!state.showUnknownDevices && state.devices.isNotEmpty())
                                            "没有找到已知设备"
                                        else
                                            "未发现设备",
                                        color = Color.White,
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                    Text(
                                        text = if (state.isScanButtonEnabled) {
                                            if (!state.showUnknownDevices)
                                                "点击开关显示所有设备"
                                            else
                                                "点击上方扫描按钮"
                                        } else {
                                            "请先授予权限并开启蓝牙"
                                        },
                                        fontSize = 14.sp,
                                        color = Color.White.copy(alpha = 0.8f),
                                        textAlign = androidx.compose.ui.text.style.TextAlign.Center
                                    )
                                }
                            }
                        }
                    } else {
                        LazyColumn(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            items(filteredDevices) { deviceItem ->
                                DeviceItemCard(
                                    deviceItem = deviceItem,
                                    onClick = {
                                        val encodedName = deviceItem.name.replace("/", "_")
                                        navController.navigate("${Routes.DEVICE_DETAIL}/${deviceItem.address}/${encodedName}")
                                    }
                                )
                            }
                        }
                    }

                    // 底部提示
                    if (!state.isScanning && filteredDevices.isNotEmpty()) {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            Text(
                                text = "提示：点击设备卡片可进入设备详情页面",
                                fontSize = 12.sp,
                                color = Color.White.copy(alpha = 0.8f),
                                modifier = Modifier.fillMaxWidth(),
                                textAlign = androidx.compose.ui.text.style.TextAlign.Center
                            )

                            if (!state.showUnknownDevices && state.devices.size > filteredDevices.size) {
                                Text(
                                    text = "已隐藏 ${state.devices.size - filteredDevices.size} 个未知设备",
                                    fontSize = 12.sp,
                                    color = Color(0xFF4CAF50),
                                    fontWeight = FontWeight.Medium,
                                    modifier = Modifier.fillMaxWidth(),
                                    textAlign = androidx.compose.ui.text.style.TextAlign.Center
                                )
                            }
                        }
                    }
                }
            }

            // 底部状态栏
            if (state.isScanButtonEnabled && !state.isScanning) {
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFF4CAF50).copy(alpha = 0.9f)
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 6.dp),
                    border = BorderStroke(1.dp, Color.White.copy(alpha = 0.3f))
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp, vertical = 12.dp),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.CheckCircle,
                            contentDescription = "就绪",
                            tint = Color.White,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Text(
                            text = "蓝牙功能已就绪，可以开始扫描设备",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.SemiBold,
                            color = Color.White
                        )
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeviceItemCard(
    deviceItem: com.hwpt.chesedemo.presentation.viewmodel.DeviceItem,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.9f),
            contentColor = Color(0xFF333333)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        border = BorderStroke(1.dp, Color.White.copy(alpha = 0.5f)),
        onClick = onClick
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // 设备名称行
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    modifier = Modifier.weight(1f),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 设备类型图标
                    Icon(
                        imageVector = when (deviceItem.type) {
                            "经典蓝牙" -> Icons.Default.BluetoothAudio
                            "BLE" -> Icons.Default.Bluetooth
                            "双模" -> Icons.Default.BluetoothConnected
                            else -> Icons.Default.DeviceUnknown
                        },
                        contentDescription = "设备类型",
                        modifier = Modifier.size(24.dp),
                        tint = Color(0xFF5A6EE1)
                    )

                    Column(
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(
                            text = deviceItem.name,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF333333),
                            maxLines = 1,
                            modifier = Modifier.fillMaxWidth()
                        )
                        Text(
                            text = "MAC: ${deviceItem.address}",
                            fontSize = 12.sp,
                            color = Color(0xFF666666),
                            maxLines = 1,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                }

                // 信号强度指示器
                Box(
                    modifier = Modifier
                        .size(52.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color(0xFF5A6EE1).copy(alpha = 0.1f)),
                    contentAlignment = Alignment.Center
                ) {
                    val signalColor = when {
                        deviceItem.rssi >= -50 -> Color(0xFF4CAF50)
                        deviceItem.rssi >= -70 -> Color(0xFFFF9800)
                        else -> Color(0xFFF44336)
                    }
                    val signalIcon = when {
                        deviceItem.rssi >= -50 -> Icons.Filled.NetworkWifi3Bar
                        deviceItem.rssi >= -70 -> Icons.Filled.NetworkWifi2Bar
                        else -> Icons.Filled.NetworkWifi1Bar
                    }

                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = signalIcon,
                            contentDescription = "信号强度",
                            tint = signalColor,
                            modifier = Modifier.size(22.dp)
                        )
                        Text(
                            text = "${deviceItem.rssi}",
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Bold,
                            color = signalColor
                        )
                    }
                }
            }

            // 设备信息行
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 设备类型标签
                Box(
                    modifier = Modifier
                        .height(28.dp)
                        .clip(RoundedCornerShape(14.dp))
                        .background(Color(0xFF5A6EE1)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = deviceItem.type,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.SemiBold,
                        color = Color.White,
                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
                    )
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.SignalCellularAlt,
                        contentDescription = "信号",
                        tint = Color(0xFF666666),
                        modifier = Modifier.size(14.dp)
                    )
                    Text(
                        text = "${deviceItem.rssi} dBm",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = Color(0xFF666666)
                    )
                }
            }

            // 点击提示
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "点击查看详情",
                    fontSize = 12.sp,
                    color = Color(0xFF5A6EE1),
                    fontWeight = FontWeight.SemiBold
                )
                Spacer(modifier = Modifier.width(4.dp))
                Icon(
                    imageVector = Icons.Default.ArrowForward,
                    contentDescription = "查看详情",
                    tint = Color(0xFF5A6EE1),
                    modifier = Modifier.size(16.dp)
                )
            }
        }
    }
}